﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyHelper;
using clf.weighing.entity;


namespace weighing
{
    public class UserDao : BaseDao<User>
    {

        #region instance

        private static UserDao? instance;
        public static UserDao Instance => instance ??= new UserDao();

        public override string GetTableName()
        {
            return TableName.user.ToString();
        }
        #endregion

        /// <summary>
        /// 获取一个默认的用户（开发者）
        /// </summary>
        /// <returns></returns>
        public User? GetDefaultUser()
        {
            String condision = UserField.role_type.ToString() + " = " + (int)UserRoleType.Developer
                + " and " + UserField.id.ToString() + "= 1";
            String sql = SqlBuilder.GetSelectSql(GetTableName(), null, condision, null, null, null, 1, 0);
            var data = Sqlite.Select<User>(sql);
            return data.FirstOrDefault();
        }
        /// <summary>
        /// 生成系统默认的账号
        /// </summary>
        /// <returns></returns>
        public User GenerateDefuaultUser()
        {
            User user = new()
            {
                id = 1,
                name = "陈龙飞",
                loginName = "chenlongfei",
                password = EncryptHelper.MD5Encrypt("rykj.123456"),
                sex = (int)UserSex.Man,
                userLevel = (int)UserLevel.Developer,
                roleType = (int)UserRoleType.Developer,
                nation = "中国",
                phone = "18087467482",
                email = "443055589@qq.com",
                qq = "443055589",
                weichat = "18087467482",
                userType = 3,
                status = 1,
                addTime = DateTime.Now,
                addUserId = 0,
                addUserName = "系统",
                affiliatedCompanyId = 0,
                company = "公司",
                remark = "系统初始化时创建",
                isDelete = 0,
                headerImg = "http://iconfont.alicdn.com/t/1565859932820.png@200h_200w.jpg",
            };
            return user;
        }

        public List<User> GetUserList()
        {
            String condition;
            if (App.CurrentUser.roleType == (int)UserRoleType.Developer)
            {
                condition = null;
            }
            else if (App.CurrentUser.roleType == (int)UserRoleType.WeighingManager)
            {
                condition = $"{UserField.affiliated_company_id} = {App.CurrentCompanyVo.Id} and " + UserField.role_type.ToString() + " in(" + (int)UserRoleType.WeighingManager + "," + (int)UserRoleType.Weighinger + ")";
            }
            else if (App.CurrentUser.roleType == (int)UserRoleType.WeighingManager)
            {
                condition = $"{UserField.affiliated_company_id} = {App.CurrentCompanyVo.Id} and " + UserField.role_type.ToString() + " in(" + (int)UserRoleType.Weighinger + ")";
            }
            else
            {
                return null;
            }
            String sql = SqlBuilder.GetSelectSqlWithSoftDeleteCondition(GetTableName(), null, condition);
            return Sqlite.Select<User>(sql);
        }

        public User? FindByPhoneOrName(String phone, String name = null)
        {
            String condition;
            if (!RegexHelper.IsMobilePhoneNumber(phone))
            {
                throw new Exception("查询的手机号码不正确");
            }

            condition = UserField.phone.ToString() + " = '" + phone + "'";

            if (!name.IsNullOrEmpty())
            {
                condition += " and  name='" + name + "'";
            }

            string sql = SqlBuilder.GetSelectSql(GetTableName(), null, condition);
            var data = Sqlite.Select<User>(sql);
            return data.FirstOrDefault();
        }
        /// <summary>
        /// 删除 用户 
        /// 决断 是事产生数据
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public int DeleteUser(User user)
        {
            if (user == null)
            {
                return 0;
            }

            if (WeighingBillDao.Instance.IsUserHasBill(user.id))
            {
                return -1;
            }
            int res = 0;
            res = Sqlite.Delete(user, true);
            try { res += UserRoleDao.Instance.DeleteByUserId((long)user.id); } catch { }
            return res;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public User? Login(string mobile, string password)
        {
            string condition = $"{UserField.password} = '{password}' and ({UserField.phone} = '{mobile}' or {UserField.login_name} = '{mobile}')";
            String sql = SqlBuilder.GetSelectSqlWithSoftDeleteCondition(GetTableName(), null, condition, null, null, null, 1);
            var list = Sqlite.Select<User>(sql);
            return list.FirstOrDefault();
        }

        /// <summary>
        /// update Password
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public int UpdatePassword(User user)
        {
            string set = UserField.password.ToString() + " = '" + user.password + "'";
            string condition = UserField.id.ToString() + " = " + user.id;
            string sql = SqlBuilder.GetUpdateSql(GetTableName(), set, condition);
            return Sqlite.Update(sql);
        }
        /// <summary>
        /// 是否已经有一个管理员
        /// </summary>
        /// <returns></returns>
        public bool IsHasManager()
        {
            string condition = $"{UserField.affiliated_company_id}={App.CurrentCompanyVo.Id} and {UserField.role_type} = {(int)UserRoleType.WeighingManager}";
            string sql = SqlBuilder.GetSelectSqlWithSoftDeleteCondition(GetTableName(), "id", condition, null, null, null, 1);
            var data = Sqlite.Select<User>(sql);
            return data.Count > 0;
        }

        /// <summary>
        /// 添加管理员
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int AddManager(User user)
        {
            UserRole ur = new UserRole
            {
                id = IdHelper.LongID,
                userId = (long)user.id,
                roleId = Constant.DefaultWeighingManagerId
            };
            string usql = SqlBuilder.GetInsertSql(user);
            string urSql = SqlBuilder.GetInsertSql(ur, TableName.sys_user_role.ToString());
            int res = Sqlite.TransactionExecute(new string[] { usql, urSql });
            return res;
        }
        /// <summary>
        /// 是否拥有权限
        /// </summary>
        /// <param name="PerKey"></param>
        /// <returns></returns>
        public bool HasPermission(String PerKey)
        {
            if (App.CurrentUser.Permissions == null || App.CurrentUser.Permissions.Count <= 0) return false;
            for (int i = 0; i < App.CurrentUser.Permissions.Count; i++)
            {
                Permission p = App.CurrentUser.Permissions[i];
                if (p.key == PerKey)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
